// 计算每日工作时长
const calculateDailyHours = (historyItems) => {
  const dailyData = {};

  historyItems.forEach((item) => {
    const date = new Date(item.lastVisitTime).toISOString().split("T")[0];
    if (!dailyData[date]) dailyData[date] = [];
    dailyData[date].push(item.lastVisitTime);
  });

  // 计算每天最早/最晚记录
  return Object.keys(dailyData).map((date) => {
    const timestamps = dailyData[date].sort();
    const workSeconds =
      (timestamps[timestamps.length - 1] - timestamps[0]) / 1000;
    return {
      date,
      hours: parseFloat((workSeconds / 3600).toFixed(2)),
      isWeekend: new Date(date).getDay() % 6 === 0, // 周末标记
    };
  });
};

// 监听历史记录请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "getHistory") {
    chrome.history.search(
      {
        text: "",
        startTime: request.startTime,
        endTime: request.endTime,
        maxResults: 10000,
      },
      (historyItems) => {
        const dailyHours = calculateDailyHours(historyItems);
        sendResponse({ dailyHours });
      }
    );
    return true; // 保持异步通道
  }
});

// 新增：打开全屏标签页
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "openFullscreen") {
      // 创建全屏标签页
      chrome.tabs.create({
        url: chrome.runtime.getURL("fullscreen.html") + `?month=${request.month}`,
        active: true
      });
    }
    
    return true;
});
